<template>
  <ElForm ref="form" class="form-page" label-width="auto" :model="props.data">
    <div class="form-page-header">
      <div class="form-page-title">{{ name }}</div>
      <div>
        <slot name="auth-button">
          <ElButton @click="router.back()">取消</ElButton>
          <ElButton type="primary" @click="submit">保存</ElButton>
        </slot>
      </div>
    </div>

    <slot :data="props.data" />
  </ElForm>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const name = computed(() => route.meta.tag)
const id = computed(() => route.params.id)
const loading = ref(false)

interface Props {
  data: object;
  getApi?: (id: string, query?: any) => Promise<any>;
  addApi?: (data: any) => Promise<any>;
  editApi?: (data: any) => Promise<any>;
}
const props = withDefaults(defineProps<Props>(), {
  data: () => ({}),
  getApi: () => Promise.resolve({}),
  addApi: () => Promise.resolve(null),
  editApi: () => Promise.resolve(null)
})

const form = ref()
const getData = async () => {
  loading.value = true
  props.getApi(id.value as string, route.query).then((res) => {
    Object.assign(props.data, res)
  }).finally(() => {
    loading.value = false
  })
}

const addSubmit = async () => {
  loading.value = true
  props.addApi(props.data).then(() => {
    router.back()
  }).finally(() => {
    loading.value = false
  })
}

const editSubmit = async () => {
  loading.value = true
  props.editApi(props.data).then(() => {
    router.back()
  }).finally(() => {
    loading.value = false
  })
}

const submit = async () => {
  await form.value?.validate() || Promise.reject()
  if (id.value) {
    editSubmit()
  } else {
    addSubmit()
  }
}

onMounted(() => {
  if (id.value) {
    getData()
  }
})

defineExpose({
  submit,
  data: props.data
})
</script>

<style scoped lang="scss">
.form-page {
  &-header {
    padding: 0 17px;
    display: flex;
    height: 62px;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1px;
    background: var(--el-color-white);
  }
  &-title {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 15px;
    color: #333333;
  }
  :deep(.el-date-editor) {
    width: 100%;
  }
  :deep(.el-input-number) {
    width: 100%;
  }
}
</style>
